from pcaspy import SimpleServer, Driver
from epics import PV,poll
from config import config,prefix,pvdb,EPICS_CA_ADDR_LIST,EPICS_CAS_SERVER_PORT
from os import environ

class monitor_PV():
    def __init__(self,driver):
        self.driver = driver
        self.log_pvname = list(driver.pvDB.keys())[0]
        self.pv_list = [PV(pvname,callback=self.onValueChange,connection_callback= self.onConnectionChange,connection_timeout=3) for pvname in config.keys()]
    def onValueChange(self,pvname=None, value=None, host=None, **kws):
        # print(f"{pvname} value:{value}")
        if config[pvname]["value"] == value:
            code = config[pvname]["code"]
            result = list(driver.getParam(reason=self.log_pvname))
            result.pop()
            result.insert(0,code)
            driver.setParam(reason=self.log_pvname,value=result)
            driver.updatePV(reason=self.log_pvname)

    def onConnectionChange(self,pvname=None, conn= None, **kws):
        print(f'PV: {pvname} \t connection status: {conn}')
class myDriver(Driver):
    def __init__(self):
        super(myDriver, self).__init__()

if __name__ == '__main__':
    environ["EPICS_CA_ADDR_LIST"] = EPICS_CA_ADDR_LIST
    environ["EPICS_CAS_SERVER_PORT"] = EPICS_CAS_SERVER_PORT
    server = SimpleServer()
    server.createPV(prefix, pvdb)
    driver = myDriver()
    _PV = monitor_PV(driver)
    while True:
        poll()
        # process CA transactions
        server.process(0.01)